package service

import (
	"MyBlogv2/blog-common/HttpCode"
	"MyBlogv2/blog-common/models"
	"MyBlogv2/blog-common/redisUtil"
	"MyBlogv2/blog-common/response"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Favorite(c *gin.Context) {
	typeOfFavorite, _ := strconv.Atoi(c.Query("type"))
	typeId, _ := strconv.Atoi(c.Query("typeId"))
	userId, _ := c.Get("userId")
	var dbCount int64
	models.Db.Model(new(models.Favorite)).Where("user_id = ? and type = ? and type_id = ?", userId, typeOfFavorite, typeId).Count(&dbCount)
	if dbCount > 0 {
		response.ResponseError(c, HttpCode.FAILURE)
		return
	}
	var favorite models.Favorite
	favorite.UserId = userId.(int)
	favorite.Type = typeOfFavorite
	favorite.TypeId = typeId
	models.Db.Model(new(models.Favorite)).Create(&favorite)
	redisUtil.AddFavoriteCount(typeId)
	response.ResponseOK(c, nil)
	return
}

func CancelFavorite(c *gin.Context) {
	typeOfFavorite, _ := strconv.Atoi(c.Query("type"))
	typeId, _ := strconv.Atoi(c.Query("typeId"))
	userId, _ := c.Get("userId")
	var dbCount int64
	models.Db.Model(new(models.Favorite)).Where("user_id = ? and type = ? and type_id = ?", userId, typeOfFavorite, typeId).Count(&dbCount)
	if dbCount == 0 {
		response.ResponseError(c, HttpCode.FAILURE)
		return
	}
	redisUtil.DelFavoriteCount(typeId)
	models.Db.Model(new(models.Favorite)).Where("user_id = ? and type = ? and type_id = ?", userId, typeOfFavorite, typeId).Delete(new(models.Favorite))
	response.ResponseOK(c, nil)
	return
}

func IsFavorite(c *gin.Context) {
	typeOfFavorite, _ := strconv.Atoi(c.Query("type"))
	typeId, _ := strconv.Atoi(c.Query("typeId"))
	userId, _ := c.Get("userId")
	var dbCount int64
	models.Db.Model(new(models.Favorite)).Where("user_id = ? and type = ? and type_id = ?", userId, typeOfFavorite, typeId).Count(&dbCount)
	if dbCount > 0 {
		response.ResponseOK(c, true)
		return
	}
	response.ResponseOK(c, false)
	return
}
